from app import db
from datetime import datetime
import json

class Goal(db.Model):
    __tablename__ = 'goals'
    
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    description = db.Column(db.Text, nullable=True)
    category = db.Column(db.String(50), nullable=True)
    target_time = db.Column(db.Integer, nullable=False)  # 目标时间（分钟）
    completed_time = db.Column(db.Integer, default=0)  # 已完成时间（分钟）
    completed = db.Column(db.Boolean, default=False)
    priority = db.Column(db.String(10), default='medium')  # 'high', 'medium', 'low'
    deadline = db.Column(db.DateTime, nullable=True)
    tags = db.Column(db.Text, default='[]')  # JSON存储标签数组
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    def to_dict(self):
        # 确保返回的时间值是整数
        completed_time = int(self.completed_time) if self.completed_time is not None else 0
        target_time = int(self.target_time) if self.target_time is not None else 0
        
        # 计算进度百分比
        progress = 0
        if target_time > 0:
            progress = min(100, (completed_time / target_time * 100))
        
        return {
            'id': self.id,
            'name': self.name,
            'description': self.description,
            'category': self.category,
            'target_time': target_time,
            'completed_time': completed_time,
            'completed': bool(self.completed),
            'priority': self.priority,
            'deadline': self.deadline.isoformat() if self.deadline else None,
            'tags': json.loads(self.tags) if isinstance(self.tags, str) else self.tags,
            'progress': progress,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }
        
    def set_tags(self, tags_data):
        """专门处理tags字段的方法"""
        if tags_data is None:
            self.tags = '[]'
        elif isinstance(tags_data, list):
            self.tags = json.dumps(tags_data)
        elif isinstance(tags_data, str):
            # 确保它是有效的JSON字符串
            try:
                json.loads(tags_data)
                self.tags = tags_data
            except:
                self.tags = '[]'
        else:
            self.tags = '[]' 